<style scoped >
.rolebody  .footer{text-align: center}
.rolebody  .footer .save{
    padding: 6px 22px;
    background: #37b3b3;
    border: 1px solid #37b3b3;
    color: #ffffff;
}
.jurisdictionbody .footer .save:hover{background: #019ea3;}
.rolebody  .footer .clear{
    padding: 6px 22px;
    background: #c7cdcd;
    border: 1px solid #c7cdcd;
    color: #ffffff;
}
.rolebody .role .ivu-form-item{margin-bottom: 0px;}
.rolebody .role .ivu-form-item .ivu-form-item-content .ivu-input-wrapper{  width:90%;}
.jurisdictionbody .footer{padding-bottom: 25px;text-align: center}
.jurisdictionbody .footer .save{
    padding: 6px 22px;
    background: #37b3b3;
    border: 1px solid #37b3b3;
    color: #ffffff;
}
.jurisdictionbody .footer .clear{
    padding: 6px 22px;
    background: #c7cdcd;
    border: 1px solid #c7cdcd;
    color: #ffffff;
}
</style>
<template>
    <div class="console-product">
        <Row class="position">
            <i-col :xs="12" :sm="10" :md="8" :lg="6" >
                <div class="ivu-breadcrumb">
                    <span class="ivu-breadcrumb-item-link">当前位置：</span>
                    <span class="ivu-breadcrumb-item-link">用户中心</span>
                    <span class="ivu-breadcrumb-item-separator">/</span>
                    <span class="ivu-breadcrumb-item-link">角色管理</span>
                </div>
            </i-col>
            <i-col class="fr">
                 <span>
                  <Button @click="addRoleMain"><i class="iconfont cofont">&#xe649;</i> 新增</Button>
                     <Modal class="rolebody" @on-cancel="cancelRole('roleValidate')" v-model="roleModal" :mask-closable="false" width="300">
                        <p slot="header" style="color: #eeebeb;" v-drag>
                            <span v-if="addRole">新增</span>
                            <span v-if="editRole">编辑</span>
                        </p>
                        <div class="role">
                            <Form ref="roleValidate" :model="roleValidate" :rules="ruleRoleCustom" label-position="left" :label-width="55">
                                <input type="hidden" name="id" v-model="roleValidate.id">
                                <Form-item label="角色名:" prop="name">
                                     <Input v-model="roleValidate.name"></Input>
                                </Form-item>
                            </Form>
                        </div>
                        <div slot="footer">
                            <div class="footer">
                                <Button class="save" v-if="addRole" :loading="modal_loading" @click="saveRole('roleValidate')">保存</Button>
                                <Button class="save" v-if="editRole" :loading="modal_loading" @click="editSaveRole('roleValidate')">保存</Button>
                            </div>
                        </div>
                    </Modal>
                </span>
            </i-col>
        </Row>
        <div class="console-product-contcent" id="contcentHeight" :style="{height:height +'px'}">
            <Form class="searchform" ref="roleForm" :model="roleForm" inline>
                <Form-item label="角色名:" prop="name" :label-width="50" style="width: 175px">
                    <Input v-model="roleForm.name" @on-enter="roleSearch"></Input>
                </Form-item>
                <Form-item>
                    <Button class="search" @click="roleSearch">搜索</Button>
                </Form-item>
            </Form>
            <Modal v-model="delModal" class-name="delect" width="250" @on-cancel="delCancel" :mask-closable="false">
                <p slot="header" style="color: #eeebeb" v-drag>
                    <span>提示框</span>
                </p>
                <p class="delbody">
                    <i class="iconfont" style="color: #f76165;font-size: 16px;">&#xe615</i>&nbsp;&nbsp;确认删除？
                </p>
                <div slot="footer">
                    <div class="footer">
                        <Button  class="save" :loading="delLoading" @click="delOK">确认</Button>
                        <Button class="clear" @click="delCancel">取消</Button>
                    </div>
                </div>
            </Modal>
            <Loading v-if="spinShow"></Loading>
            <Table v-if="tableShow"  stripe border :columns="roleColumns" ref="roleData" :data="roleData"></Table>
            <Modal v-model="jurisdictionModal" class="jurisdiction" @on-cancel="canceljurisdiction"  width="600" :mask-closable="false">
                <p slot="header" style="color: #eeebeb" v-drag>
                    <span>授权</span>
                </p>
                <div class="jurisdictionbody">
                    <Tree @on-check-change="selectChange" @on-select-change="selectnode" :data="jurisdictionData" show-checkbox></Tree>
                    <div class="footer">
                        <Button class="save" :loading="modal_loading" @click="savejurisdiction">授权</Button>
                        <Button class="clear" @click="canceljurisdiction">取消</Button>
                    </div>
                </div>
                <div slot="footer"></div>
            </Modal>
        </div>
        <Row style="background-color: #ffffff;margin-top: 1px;">
            <Col>
            <div v-if="tableShow" class="tablepage clearfix">
                <div class="fl">
                    <span>共</span>
                    <span class="num">{{total}}</span>
                    <span>条记录</span>
                    <span>{{currentPage}}/{{pageTotal}}页</span>
                </div>
                <div class="fr">
                    <Page :total="total" :page-size="pageSize" :current="currentPage" placement="top" show-elevator show-sizer @on-change="changePage" @on-page-size-change="changeSize"></Page>
                </div>
            </div>
            </Col>
        </Row>
    </div>
</template>
<script>
    // 导入要用到的子组件
    import Loading from '../../components/loading'
    export default {
        data () {
            return {
                modal_loading: false,
                total: 0,//总条数
                currentPage: 1,//当前页
                pageTotal: 1,//总页数
                pageSize: 10,//默认每页显示数量
                height: 1000,//表单高度
                spinShow: true,//加载层，默认显示
                delModal: false,//删除弹窗
                delLoading:false,//删除
                delId:'',//删除id
                tableShow: false,//表格层，默认隐藏
                roleForm: {//菜单管理条件查询
                    name:''
                },
                roleData:[],//数据
                roleColumns:[
                    {
                        width:'4%',
                        title: '序号',
                        type:'index'
                    },
                    {
                        width:'25%',
                        title: '角色名',
                        key: 'name',
                        render: (h, params) => {
                            return h('Tooltip', {
                                props: {
                                    content: params.row.name,
                                    placement:"bottom-start"
                                }
                            }, [h('span', params.row.name)]);
                        }
                    },
                    {
                        width:'26%',
                        title: '创建人',
                        key: 'creatBy',
                        render: (h, params) => {
                            return h('Tooltip', {
                                props: {
                                    content: params.row.creatBy,
                                    placement:"bottom-start"
                                }
                            }, [h('span', params.row.creatBy)]);
                        }
                    },
                    {
                        width:'25%',
                        title: '更新时间',
                        key: 'creatTime',
                        render: (h, params) => {
                            const text = params.row.creatTime != null ? new Date(params.row.creatTime).format('yyyy-MM-dd hh:mm:ss') : "";
                            return h('Tooltip', {
                                props: {
                                    content: text,
                                    placement:"bottom-start"
                                }
                            }, [h('span', text)]);
                        }
                    },
                    {
                        width:'20%',
                        title: '操作',
                        key: 'id',
                        render: (h, params) => {
                            return h('div', [
                                h('Button',
                                    {
                                        class:"blue",
                                        on: {
                                            click: () => {
                                                this.editRoleMain(params.row.id)
                                            }
                                        }
                                    },
                                    [
                                        h('i', {
                                            class : 'iconfont icon-bianji'
                                        }),
                                        h("span",'编辑')
                                    ]),
                                h('Button',
                                    {
                                        class:"red",
                                        on: {
                                            click: () => {
                                                this.remove(params.row)
                                            }
                                        }
                                    },
                                    [
                                        h('i', {
                                            class : 'iconfont icon-qingkong'
                                        }),
                                        h("span",'删除')
                                    ]),
                                h('Button',
                                    {
                                        class:"blue",
                                        on: {
                                            click: () => {
                                                this.openjuris(params.row.id)
                                            }
                                        }
                                    },
                                    [
                                        h('i', {
                                            class : 'iconfont icon-kshouquanjiaose'
                                        }),
                                        h("span",'授权')
                                    ])
                            ]);
                        }
                    }
                ],
                roleModal:false,//新增窗口弹窗
                addRole:false,//新增
                editRole:false,//编辑
                roleValidate:{//新增数据
                    name:'',
                    id:''
                },
                ruleRoleCustom:{//验证
                    name: [
                        {required: true, message: '请输入角色名', trigger: 'blur'},
                        { type: 'string', max: 100, message: '角色名长度不能大于100位', trigger: 'blur' }
                    ]
                },
                jurisdictionModal:false,//权限管理弹窗
                jurisdictionData:[],
                jurisdiction:{
                    roleId:'',
                    permissionIds:''
                },
                idList:'',
            }
        },
        //所需子组件
        components: {
            Loading
        },
        created:function(){
            var width = window.innerWidth;
            if(width >1600){
                this.height=window.innerHeight-200;
            }else if(width > 1440 && width <=1600){
                this.height=window.innerHeight-180;
            }else if(width > 1366 && width <=1440){
                this.height=window.innerHeight-172;
            }else if(width > 1280 && width <=1366){
                this.height=window.innerHeight-166;
            }else if(width > 1024 && width <=1280){
                this.height=window.innerHeight-162;
            }else{
                this.height=window.innerHeight-151;
            }
            if(window.innerWidth > 1600){
                this.pageSize = 20;
            }
            this.roleData = this.roleTableData(this.roleForm,this.currentPage,this.pageSize)
        },
        mounted() {

        },
        methods: {
            //查询物流数据，条件，当前页，每页显示多少条
            roleTableData (formData,currentPage,pageSize) {
                this.spinShow=true;
                this.tableShow = false;
                var name = formData.name;//角色名
                let data = {
                    params: {
                        pageIndex : currentPage,
                        pageSize : pageSize,
                        name : name
                    }
                };
                axios.get('/roles',data).then(res => {
                    this.total=res.data.total;
                    this.pageTotal=Math.ceil(res.data.total / pageSize);
                    this.roleData = res.data.data;
                    this.spinShow=false;
                    this.tableShow = true;
                }).catch(err =>{
                })
            },
            //条件查询
            roleSearch () {
                this.currentPage = 1;
                this.roleData = this.roleTableData(this.roleForm,this.currentPage,this.pageSize);
            },
            //改变页数
            changePage: function (page) {
                this.currentPage = page;
                this.roleData = this.roleTableData(this.roleForm,this.currentPage,this.pageSize);
            },
            //改变每页显示多少条
            changeSize: function (pageSize) {
                this.currentPage = 1;
                this.pageSize = pageSize;
                this.pageTotal = Math.ceil(this.total / this.pageSize);
                this.roleData = this.roleTableData(this.roleForm,this.currentPage,this.pageSize);
            },
            //根据ID删除权限管理列表
            remove(column){
                this.delModal=true;
                this.delId = column.id;
            },
            delOK(){
                this.delLoading = true;
                axios.delete('/role/'+this.delId,{params: {id:this.delId}}).then(res => {
                    this.delLoading = false;
                    this.delModal=false;
                    this.roleData = this.roleTableData(this.roleForm,this.currentPage,this.pageSize);
                }).catch(err =>{
                    this.$Message.error({content: err,duration: 0,closable:true});
                    this.delLoading = false;
                });
            },
            delCancel() {
                this.delModal=false;
                this.delId = '';
            },
            //新增菜单
            addRoleMain() {
                this.addRole = true;
                this.editRole = false;
                this.roleModal = true;
            },
            //保存新增
            saveRole(name){
                this.modal_loading = true;
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        axios.post('/roles', this.roleValidate).then(res => {
                            this.modal_loading = false;
                            this.roleModal = false;
                            this.addRole=false;
                            this.$refs[name].resetFields();
                            this.roleData = this.roleTableData(this.roleForm,this.currentPage,this.pageSize);
                        }).catch(err =>{
                            this.modal_loading = false;
                            this.$Message.error({content: err,duration: 0,closable:true});
                        });
                    } else {
                        this.modal_loading = false;
                    }
                })
            },
            //根据ID编辑
            editRoleMain(column) {
                this.addRole = false;
                this.editRole = true;
                axios.get('/roles/'+column).then(res => {
                    this.roleValidate = res.data;
                    this.roleModal=true;
                }).catch(err =>{
                })
            },
            //保存编辑
            editSaveRole (name) {
                this.modal_loading = true;
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        axios.put('/roles', {id:this.roleValidate.id,name:this.roleValidate.name}).then(res => {
                            this.modal_loading = false;
                            this.roleModal = false;
                            this.editRole=false;
                            this.$refs[name].resetFields();
                            this.roleData = this.roleTableData(this.roleForm,this.currentPage,this.pageSize);
                        }).catch(err =>{
                            this.modal_loading = false;
                            this.$Message.error({content: err,duration: 0,closable:true});
                        });
                    } else {
                        this.modal_loading = false;
                    }
                });
            },
            //关闭新增
            cancelRole(name){
                this.modal_loading = false;
                this.roleModal = false;
                this.addRole = false;
                this.editRole = false;
                this.$refs[name].resetFields();
            },
            //授权
            openjuris(id){
                this.jurisdiction.roleId = id;
                axios.get('/role/'+id+'/tree').then(res => {
                    this.jurisdictionData = res.data;
                    this.jurisdictionModal=true;
                    setTimeout(() => {//防止父节点没选中
                        $(".ivu-tree ul.ivu-tree-children ul.ivu-tree-children ul.ivu-tree-children li label.ivu-checkbox-wrapper:first").click();
                        $(".ivu-tree ul.ivu-tree-children ul.ivu-tree-children ul.ivu-tree-children li label.ivu-checkbox-wrapper:first").click();
                    }, 1000);
                }).catch(err =>{
                })
            },
            //取消授权
            canceljurisdiction(){
                this.jurisdictionModal = false;
                this.jurisdictionData = [];
                this.jurisdiction = {
                    roleId:'',
                    permissionIds:''
                };
                this.idList = "";
            },
            //选择授权节点
            selectChange(selection) {
                if(selection.length==0){
                    this.idList = "";
                }else{
                    this.idList = "";
                    for(var i in selection){
                        if(selection[i].id != undefined){
                            this.idList += selection[i].id + ",";
                        }
                    }
                }
            },
            selectnode(selection){
                var str = this.idList;
                $(".ivu-tree-title").each(function() {
                    if($(this).text() == selection[0].title){
                        if($(this).prev().find("span.ivu-checkbox").hasClass("ivu-checkbox-indeterminate")){
                            str += selection[0].id + ",";
                        }
                    }
                })
                this.idList = str;
            },
            toggleexpand(selection){
            },
            //保存授权
            savejurisdiction(name){
                this.modal_loading = true;
                if(this.idList == ""){
                    $(".ivu-checkbox").each(function() {
                        if(!$(this).hasClass("ivu-checkbox-checked") && !$(this).hasClass("ivu-checkbox-indeterminate")){//没有选择
                            $(this).click();
                            $(this).click();
                            return false;
                        }
                    });
                }
                $(".ivu-checkbox-indeterminate").each(function () {
                    $(this).parent().next().click();
                });
                if (this.idList.length > 0) {
                    this.idList = this.idList.substring(0, this.idList.length - 1);
                    Array.prototype.unique = function () {
                        var res = [];
                        var json = {};
                        for (var i = 0; i < this.length; i++) {
                            if (!json[this[i]]) {
                                res.push(this[i]);
                                json[this[i]] = 1;
                            }
                        }
                        return res;
                    };
                    if(this.idList.length != 0){
                        var arr = this.idList.split(",");
                        this.idList = arr.unique().join(",");
                    }
                    this.jurisdiction.permissionIds = this.idList;
                    axios.put('/permission/putRole',this.jurisdiction).then(res => {
                        this.modal_loading = false;
                        this.jurisdictionModal = false;
                        this.jurisdictionData=[];
                        this.jurisdiction = {
                            memberId:'',
                            permissionIds:''
                        };
                        this.idList = "";
                    }).catch(err =>{
                        this.idList = "";
                        this.$Message.error({content: err,duration: 0,closable:true});
                        this.modal_loading = false;
                    });
                }else{
                    this.$Message.error("至少选择一个");
                    this.modal_loading = false;
                }
            },
        }
    }
</script>